#!/usr/bin/env python

'''
    Convert the stripped HTML files into mapped files.

    The autosort script expects all the id's to be a sequential range from
    1 to the number of entries.
'''

import os, sys

# Value to rank SRC submission tags.  A lower number will result in a tighter
# correspondence between SRC submissions and jurors
SRC_RANK  = 2

# Juror rank for SRC expertise.  1 = expert, 2 = knowledgeable
SRC_EXPERT = 1

Headers = {
  'conflict'  : 'rev id, sub id',
  'request'   : 'rev id, sub id',
  'reviewer-topics' : 'rev id, topic id, strength (1=expert, 2=knowledgeable)',
  'submission-topics' : 'sub id, topic id, rank (1=first_topic, 2=second...)',
}

def createMapFile(style):
    sfile = 'sis-%ss.txt' % style
    mfile = 'map-%ss.txt' % style
    if not os.path.exists(sfile):
        print 'Missing input file:', sfile
        sys.exit(1)
    lines = open(sfile, 'r').readlines()
    ofp = open(mfile, 'w')
    ofp.write('# %s id, %s name\n' % ( style, style) )
    map = {}
    count = 0
    for l in lines:
        args = l.split()
        if len(args) > 1:
            count += 1
            map[args[0]] = str(count)
            ofp.write('%d %s\n' % ( count, ' '.join(args[1:])))
    ofp = open('unmap-%ss.txt' % style, 'w')
    for m in map:
        ofp.write('%s %s\n' % (m, map[m]))
    return map

def translate(file, maps, style, reverse=False):
    sfile = 'sis-%s.txt' % file
    mfile = 'map-%s.txt' % file
    if not os.path.exists(sfile):
        print 'Missing input file:', sfile
        sys.exit(1)
    lines = open(sfile, 'r').readlines()
    ofp = open(mfile, 'w')
    ofp.write('# ' + Headers[file] + '\n')
    n = len(maps)
    olines = []
    missing = {}
    for l in lines:
        args = l.split()
        ok = True
        for i in range(n):
            sis_id = args[i]
            args[i] = maps[i].get(sis_id, None)
            if not args[i]:
                ok = False
                if not missing.has_key(sis_id):
                    missing[sis_id] = True
                    print '*** Error in file', sfile,
                    print ' -- Near line: "%s"' % l.strip()
                    print "\tNo %s with id %s" % (style[i], str(sis_id))
                break
        if ok:
            if reverse:
                args.reverse()
            olines.append(' '.join(args))

    def cmpLines(l1, l2):
        a1 = l1.split()
        a2 = l2.split()
        for i in range(len(a1)):
            v1 = int(l1.split()[0])
            v2 = int(l2.split()[0])
            if v1-v2 != 0:
                return v1-v2
        return 0
    olines.sort(cmpLines)
    ofp.write('\n'.join(olines))
    ofp.write('\n')

def appendSRC(smap, rmap, tmap):
    '''
        The SRC submissions should be looked at by the SRC judges.  Therefore,
        we add a magical topic which has a fairly strong rank that should get
        the SRC jurors to be more likely to look at the SRC submissions
    '''
    SRC_ID = len(tmap) + 1
    open('map-topics.txt', 'a').write('%d SRC\n' % SRC_ID)
    src_subs = open('sis-SRC.txt', 'r').readlines()
    fp = open('map-submission-topics.txt', 'a')
    for sub_id in src_subs:
        id = sub_id.strip().split()
        if len(id) > 0:
            map_id = smap.get(id[0], None)
            if map_id:
                fp.write('%s %d %d\n' % (map_id, SRC_ID, SRC_RANK))
            else:
                print 'WARNING: Submission %s marked as SRC but not in complete list' % id

'''
files = [
    FileInfo('conflict',        [ REV_ID, SUB_ID ]),
    FileInfo('request',         [ REV_ID, SUB_ID ]),
    FileInfo('reviewer-topics', [ REV_ID, TOP_ID ]),
    FileInfo('submission-topics',       [SUB_ID, TOP_ID]),
]
'''

def main():
    print 'Creating reviewer, submission and topic maps'
    rmap = createMapFile('reviewer')
    smap = createMapFile('submission')
    tmap = createMapFile('topic')
    # Now translate each file
    # The conflict & request files are reversed for the autosort
    translate('conflict', [rmap, smap], ['Reviewer', 'Submission'])
    translate('request', [rmap, smap], ['Reviewer', 'Submission'])
    translate('reviewer-topics', [rmap, tmap], ['Reviewer', 'Topic'])
    translate('submission-topics', [smap, tmap], ['Submission', 'Topic'])
    appendSRC(smap, rmap, tmap)
    print 'SUCCESS\n'
    print 'Now copy the map files to the autosort location and sort'

if __name__ == "__main__":
    main()
